package com.maycur.ctrip.service.impl;

import com.maycur.ctrip.domain.SimplifiedSubsidiary;
import com.maycur.ctrip.domain.SimplifiedUser;
import com.maycur.ctrip.mybatis.mapper.UserMapper;
import com.maycur.ctrip.service.RedisService;
import com.maycur.ctrip.service.UserService;
import com.maycur.ctrip.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * Created by JoeyXin on 7/8/16.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{
    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public SimplifiedUser getUser(String entCode, String userCode) {
        SimplifiedUser user = redisService.getGeneric(Constant.SIMPLIFIED_USER_IN_REDIS + entCode + "_" + userCode, SimplifiedUser.class);

        if(user == null) {
                user = userMapper.selectUser(entCode, userCode);

            if(StringUtils.isEmpty(user.getDefaultSubsidiaryCode())) {
                //user没有设置default subsidiary
                SimplifiedSubsidiary subsidiary = userMapper.selectOneSubsidiary(entCode, userCode);
                user.setDefaultSubsidiaryCode(subsidiary.getCode());
                user.setDefaultBaseCcy(subsidiary.getBaseCcy());
            }
            if(user != null) {
                redisService.saveGenericWithExpireTime(Constant.SIMPLIFIED_USER_IN_REDIS + entCode + "_" + userCode, user, Constant.SIMPLIFIED_USER_EXPIRED_MINUTES, TimeUnit.MINUTES);
            }
        }

        return user;
    }
}
